#!/usr/bin/python
# plot_logN.py

import math
import numpy
from matplotlib import use as useBackend
useBackend('Agg')
import matplotlib.pyplot as ppt


def cheat111():
    '''Cheat to clear the plot.'''
    ppt.subplot(311)
    ppt.plot([0,1],[1,2])
    ppt.subplot(131)
    ppt.plot([0,1],[1,2])
    ppt.subplot(111)

def plottable(N, delN):
    '''Transforms N from units of deg^-2 to deg^-2 dMv^-1.'''
    N = numpy.array(N, dtype=float)
    delN = numpy.array(delN, dtype=float)
    plotN = numpy.log10((N**10)/delN)
    return plotN


def plot(simpars, phypars, N, allskyN):
    '''Shows a slice of GM_logN's results.'''
    for i in simpars:
        cmd = "%s = simpars['%s']" % (i,i)
        exec cmd
    for i in phypars:
        cmd = "%s = phypars['%s']" % (i,i)
        exec cmd
    # Generic labels
    blabel = '0 -> b -> $\pi$/2'
#    Nlabel = 
    # Plot two slices each for a bright and dim population
    brightN = N[0]
    dimN = N[-1]
    brightdata = N_bM[0]
    dimdata = N_bM[-1]
    plotbrightcalc = plottable(brightN, delMvVals[0])
    plotdimcalc = plottable(dimN, delMvVals[-1])
    plotbrightdata = plottable(brightdata, vanilladelMvVals[0])
    plotdimdata = plottable(dimdata, vanilladelMvVals[-1])

    # N
    cheat111()
    ppt.hold(True)
    ppt.subplot(211)
    calc = ppt.plot(ba, plotbrightcalc, marker=',')
    data = ppt.plot(bvals, plotbrightdata, ls='None', marker='.')
#    ppt.plot(ba, brightN)
#    ppt.plot(bvals, brightdata, ls='None', marker='.')
    ppt.legend([data, calc], ["Data", "Calculated"], loc=4)
    ppt.ylabel('$\log_{10}($bright stars deg$^{-2}$ dMv$^{-1})$')
    ppt.xlabel(blabel)
    ppt.subplot(212)
    calc = ppt.plot(ba, plotdimcalc, marker=',')
    data = ppt.plot(bvals, plotdimdata, ls='None', marker='.')
#    ppt.plot(ba, dimN)
#    ppt.plot(bvals, dimdata, ls='None', marker='.')
    ppt.legend([data, calc], ["Data", "Calculated"], loc=4)
    ppt.ylabel('$\log_{10}($dim stars deg$^{-2}$ dMv$^{-1})$')
    ppt.xlabel(blabel)
    plotname = outdir+'logNslices.pdf'
    ppt.savefig(plotname)

    cheat111()
    ppt.imshow(N)
    ppt.colorbar()
    ppt.ylabel('25 -> Apparent magnitude -> 12')
    ppt.xlabel(blabel)
    plotname = outdir+'logN.pdf'
    ppt.savefig(plotname)

    # allskyN
    cheat111()
    plotcalc = plottable(allskyN, delMvVals)
    plotdata = plottable(allsky, vanilladelMvVals)
    calc = ppt.plot(MvVals, plotcalc, marker=',')
    data = ppt.plot(vanillaMvVals, plotdata, ls='None', marker='.')
#    calc = ppt.plot(MvVals, allskyN, marker=',')
#    data = ppt.plot(vanillaMvVals, allsky, ls='None', marker='.')
    ppt.legend([data, calc], ["Data", "Calculated"], loc=4)
    ppt.title('All sky averages')
    ppt.xlabel('Apparent magnitude')
    ppt.ylabel('$\log_{10}($stars deg$^{-2}$ dMv$^{-1})$')
    plotname = outdir+'logallskyN.pdf'
    ppt.savefig(plotname)
